<template>
  <div class="page-header-index-wide">
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="月销售额" :total="monthXiao">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div>
            <trend v-if="zhouToYear>=0?flag='up':flag='down'" :flag="flag" style="margin-right: 16px;">
              <span slot="term">周同比</span>
              {{zhouToYear}}%
            </trend>
            <trend v-if="zhouToYear>=0?flag='up':flag='down'" :flag="flag">
              <span slot="term">日同比</span>
              {{dayToYear}}%
            </trend>
          </div>
          <template slot="footer">
            日均销售额
            <span>￥ {{dayXiao}}</span>
          </template>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="一周出货量" :total="weeklyShipments | NumberFormat">
          <a-tooltip title="指标说明" slot="action">
            <a-icon type="info-circle-o"/>
          </a-tooltip>
          <div>
            <mini-area />
          </div>
          <template slot="footer">
            日均出货量
            <span>{{ (weeklyShipments / 7) | NumberFormat }}</span>
          </template>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="本周支付笔数" :total="ordersVO.totalOrders | NumberFormat">
          <div>
            <mini-bar :height="40" ref="miniBar" />
          </div>
          <template slot="footer">
            转化率
            <span>{{ ordersVO.orderConversionRate == null ? 0 : ordersVO.orderConversionRate }}%</span>
          </template>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="当月核销笔数" :total="heXiaoCount">
          <div>
            <mini-progress color="rgb(19, 194, 194)" :target="80" :percentage="78" :height="8" />
          </div>
          <template slot="footer">
            日均核销笔数
            <span>￥ {{ heXiaoCount / 30 }}</span>
          </template>
        </chart-card>
      </a-col>
    </a-row>

    <a-card  :bordered="false" :body-style="{ padding: '0' }">
      <div class="salesCard">
        <a-tabs
          default-active-key="1"
          size="large"
          v-model="activeKey"
          @change="chartChange"
          :tab-bar-style="{ marginBottom: '24px', paddingLeft: '16px' }"
        >
          <!-- <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item" v-if="showPrise">
              <a-radio-group :value="barType" @change="statisticst">
                <a-radio-button value="year">按年统计</a-radio-button>
                <a-radio-button value="month">按月统计</a-radio-button>
                <a-radio-button value="week">按周统计</a-radio-button>
              </a-radio-group>
            </div>
            <a-range-picker
              id="manytime"
              :style="{ width: '256px' }"
              :ranges="{
                今日: [moment().startOf('day'), moment().endOf('day')],
                本周: [moment().startOf('week'), moment().endOf('week')],
                本月: [moment().startOf('month'), moment().endOf('month')]
              }"
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              @ok="getStartTimeAndEndTime"
            />
          </div> -->
          <a-tab-pane tab="柱状图" :key="1">
            <a-row :gutter="24">
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <div id="myChart" :style="{ width: '117%', height: '400px' }"></div>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="门店销售排行榜" :list="rankList" />
              </a-col>
              <div></div>
            </a-row>
          </a-tab-pane>
          <!-- <a-tab-pane tab="订单情况" :key="2">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <div id="myPai" :style="{ width: '500px', height: '500px' }"></div>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="门店销售排行榜" :list="rankList" />
              </a-col>
            </a-row>
          </a-tab-pane> -->
        </a-tabs>
      </div>
    </a-card>

    <a-row>
      <a-col :span="24">
        <a-card :loading="loading" :bordered="false" title="最近一月销售额统计" :style="{ marginTop: '24px' }">
          <zhexiantu></zhexiantu>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import ChartCard from '@/components/ChartCard'
import echarts from 'echarts'
import ACol from 'ant-design-vue/es/grid/Col'
import ATooltip from 'ant-design-vue/es/tooltip/Tooltip'
import MiniArea from '@/components/chart/MiniArea'
import MiniBar from '@/views/echarts/MiniBar'
import MiniProgress from '@/components/chart/MiniProgress'
import RankList from '@/components/chart/RankList'
import Bar from '@/components/chart/Bar'
import LineChartMultid from '@/components/chart/LineChartMultid'
import HeadInfo from '@/components/tools/HeadInfo.vue'
import Pie from '@/components/chart/Pie'
import Trend from '@/components/Trend'
import { getAction } from '@/api/manage'
import moment from 'moment'
import zhexiantu from './zhexiantu'
const rankList = []
const barData = []
for (let i = 0; i < 12; i += 1) {
  barData.push({
    x: `${i + 1}月`,
    y: Math.floor(Math.random() * 1000) + 200
  })
}
export default {
  name: 'Analysis',
  components: {
    ATooltip,
    ACol,
    ChartCard,
    MiniArea,
    MiniBar,
    MiniProgress,
    RankList,
    Bar,
    Trend,
    LineChartMultid,
    HeadInfo,
    Pie,
    zhexiantu
  },
  data() {
    return {
      flag: '',
      weeklyShipments: undefined,
      showPrise: true,
      activeKey: 1,
      monthXiao: '0',
      dayXiao: '0',
      dayToYear: '0',
      zhouToYear: '0',
      heXiaoCount: '0',
      ordersVO: {},
      startTime: '',
      endTime: '',
      loading: true,
      center: null,
      rankList,
      barData,
      loginfo: {},
      visitFields: [],
      visitInfo: [],
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      // 查询条件
      queryParam: {},
      // 数据集
      countSource: [],
      // 柱状图
      barType: 'year',
      barDateY: [],
      barDateX: [],
      barValue: [],
      // 饼状图
      pieType: 'year',
      pieDate: ['month', 'month'],
      pieValue: [],
      // 统计图类型
      tabStatus: 'bar',
      url: {
        getYearCountInfo: '/payChart/merchant/monthofYear',
        getMonthCountInfo: '/payChart/merchant/month',
        getweekCountInfo: '/payChart/merchant/zhou',
        getCabinetCountInfo: '/api/report/getCabinetCountInfo'
      }
    }
  },
  mounted() {
    setTimeout(() => {
    this.getMonthofDayXiao()
    this.getRightRanking()
    this.getZiFuData()
    this.getHeXiaoCount()
    this.getHotCommodity()
      }, 1200)

    // let url = this.url.getYearCountInfo
    // this.loadDate(url, 'year', {  type: 4 })
  },
  beforeUpdate() {
    this.getData(this.startTime, this.endTime)
  },
  created() {
    let url = this.url.getYearCountInfo
    this.loadDate(url, 'year', { type: 4 })
    setTimeout(() => {
      this.loading = !this.loading
    }, 1000)

  },
  activated() {
    let url = this.url.getYearCountInfo
    this.loadDate(url, 'year', { type: 4 })
    //
  },
  methods: {
    chartChange(key) {
      if (key == 1) {
        this.showPrise = true
      } else {
        this.showPrise = false
      }
    },
    getZiFuData() {
      let this_ = this
      this.$nextTick(function() {
        getAction('/orderChart/getOrderConversionRate')
          .then(res => {
            if (res.success) {
              //遍历数组，取出数据
              for (let key in res.data) {
                if (key == 'ordersVO') {
                  this_.ordersVO = res.data[key]
                }
              }
            }
          })
          .catch(err => {})
      })
    },
    getHotCommodity() {
      let this_ = this
      getAction('/payChart/getHotCommodity').then(res => {
        let count = 0
        if (res.success) {
          for (let key in res.result) {
            count = count + res.result[key]
            this_.weeklyShipments = count
          }
        }
      })
    },
    getHeXiaoCount() {
      let this_ = this
      getAction('/orderChart/getOrderCancellationData').then(res => {
        if (res.success) {
          this_.heXiaoCount = res.data.toString()
        }
      })
    },
    getMonthofDayXiao() {
      let this_ = this
      getAction('/payChart/getSalesVolumes').then(res => {
        if (res.success) {
          this_.monthXiao = res.result.monthSalesVolumes
          this_.dayXiao = res.result.avgDailySaleSVolumes
          this_.dayToYear = res.result.dayToYear
          this_.zhouToYear = res.result.zhouToYear
        }
      })
    },
    //右边排行榜开始
    getRightRanking() {
      let this_ = this
      let month = { type: 3 }
      getAction('/payChart/merchant/rightmonth', month).then(res => {
        this.rankList = []
        if (res.success) {
          for (let key in res.result) {
            this.rankList.push({
              name: res.result[key].shopName,
              total: res.result[key].presentPrice / 100
            })
          }
        }
      })
    },
    //右边排行榜结束
    //饼状图
    moment,
    getStartTimeAndEndTime(dates) {
      this.startTime = moment(dates[0]._d).format('YYYY-MM-DD HH:mm:ss')
      this.endTime = moment(dates[1]._d).format('YYYY-MM-DD HH:mm:ss')
      this.getData(this.startTime, this.endTime)
    },
    drawmyPai(statusName, data) {
      // 基于准备好的dom，初始化echarts实例
      let myPai = this.$echarts.init(document.getElementById('myPai'))
      // 绘制图表
      myPai.setOption({
        title: {
          // text: '订单情况',
          subtext: '',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: statusName
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: data,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    },
    getData(startTime, endTime) {
      if (startTime == '' && endTime == '') {
        startTime = moment()
          .startOf('month')
          .format('YYYY-MM-DD HH:mm:ss')
        endTime = moment()
          .endOf('month')
          .format('YYYY-MM-DD HH:mm:ss')
      }
      let this_ = this
      this.$nextTick(function() {
        getAction('/orderChart/pieChart', { startTime, endTime })
          .then(res => {
            if (res.success) {
              //遍历数组，取出数据
              let statusName = [],
                data = [],
                obj = {}
              for (let key in res.data) {
                statusName.push(key)
                obj = { value: res.data[key], name: key }
                data.push(obj)
              }
              this_.drawmyPai(statusName, data)
            } else {
              this_.drawmyPai([], [], [], [])
              this_.$message.warn('无结果')
            }
          })
          .catch(err => {})
      })
    },
    // 以上饼状图
    // 以下为销售额用到的方法
    loadDate(url, type, param) {
      getAction(url, param).then(res => {
        if (res.success) {
          this.countSource = []
          if (type === 'year') {
            this.getYearCountSource(res.result)
          }
          if (type === 'month') {
            this.getMonthCountSource(res.result)
          }
          if (type === 'week') {
            this.getWeekCountSource(res.result)
          }
        }
      })
    },
    getYearCountSource(data) {
      console.log('年回调')
      this.barDateX = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
      this.barDateY = []
       for(let i in this.barDateX){
            this.barDateY[i-1]=data[i]
        }
      // for (let key in data) {
      //   this.barDateX.push(key)
      //   this.barDateY.push(data[key] / 100)
      // }
      this.drawLine()
    },
    getMonthCountSource(data) {
      console.log('月回调')
      this.barDateX = []
      this.barDateY = []
      for (let key in data) {
        this.barDateX.push(key)
        this.barDateY.push(data[key] / 100)
      }
      this.drawLine()
    },
    getWeekCountSource(data) {
      console.log('周回调')
      this.barDateX = []
      this.barDateY = []
      let weekDay = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      for (let key in data) {
        this.barDateY.push(data[key] / 100)
        let myDate = new Date(Date.parse(key))
        this.barDateX.push(weekDay[myDate.getDay()])
      }
      this.drawLine()
    },

    // 选择统计图类别----1
    callback(key) {
      if (key === '1') {
        this.tabStatus = 'bar'
        this.queryDatebar()
      } else {
        this.tabStatus = 'pie'
        this.queryDatepie()
      }
    },
    // 选择统计类别  ----a
    statisticst(e) {
      if (this.tabStatus === 'pie') {
        this.pieType = e.target.value
        this.queryDatepie()
      } else {
        this.barType = e.target.value
        this.queryDatebar()
      }
    },
    // 按月（年,周）份查询----2 b 给url写参数
    queryDatebar() {
      if (this.barType === 'year') {
        this.getUrl(this.barType, { type: 4 })
      } else if (this.barType === 'month') {
        this.getUrl(this.barType, { type: 3 })
      } else if (this.barType === 'week') {
        this.getUrl(this.barType, { type: 2 })
      }
    },
    queryDatepie() {
      if (this.barType === 'year') {
        this.getUrl(this.barType, { type: 4 })
      } else if (this.barType === 'month') {
        this.getUrl(this.barType, { type: 3 })
      } else if (this.barType === 'week') {
        this.getUrl(this.barType, { type: 2 })
      }
    },
    //查询时间
    searchReset() {
      console.log(this.tabStatus)
      if (this.tabStatus === 'pie') {
        this.pieValue = []
      } else {
        this.barValue = []
      }
      this.getUrl(this.barType, {})
    },
    // 选择请求url
    getUrl(type, param) {
      console.log('输出参数' + JSON.stringify(param))
      let url = ''
      if (type === 'year') {
        url = this.url.getYearCountInfo
      }
      if (type === 'month') {
        url = this.url.getMonthCountInfo
      }
      if (type === 'week') {
        url = this.url.getweekCountInfo
      }
      if (type === 'cabinet') {
        url = this.url.getCabinetCountInfo
      }
      this.loadDate(url, type, param)
    },
    // 选择月份日期
    handleBarDate(value, mode) {
      this.barValue = value
      this.barDate = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
    },
    handlePieDate(value, mode) {
      this.pieValue = value
      this.pieDate = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
    },
    drawLine() {
      let myChart = echarts.init(document.getElementById('myChart'))
      myChart.setOption({
        title: {
          text: '   商店收益报表统计'
        },
        tooltip: {},
        xAxis: {
          data: this.barDateX
        },
        yAxis: {},
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: this.barDateY,
            itemStyle: {
              normal: {
                color: '#38A0FF'
              }
            }
          }
        ]
      })
    }
    //以上为销售额用到的方法
  }
}
</script>

<style lang="scss" scoped>
.rank {
  height: 350px !important;
  overflow: auto !important;
}
.circle-cust {
  position: relative;
  top: 28px;
  left: -100%;
}
.extra-wrapper {
  line-height: 55px;
  padding-right: 24px;

  .extra-item {
    display: inline-block;
    margin-right: 24px;

    a {
      margin-left: 24px;
    }
  }
}

/* 首页访问量统计 */
.head-info {
  position: relative;
  text-align: left;
  padding: 0 32px 0 0;
  min-width: 125px;

  &.center {
    text-align: center;
    padding: 0 32px;
  }

  span {
    color: rgba(0, 0, 0, 0.45);
    display: inline-block;
    font-size: 0.95rem;
    line-height: 42px;
    margin-bottom: 4px;
  }
  p {
    line-height: 42px;
    margin: 0;
    a {
      font-weight: 600;
      font-size: 1rem;
    }
  }
}
</style>
